# -*- coding: utf-8 -*-
import os
import shutil
import logging
import maya.cmds as mc
from Qt.QtWidgets import *
from liberQt.messagebox import MessageBox
from liberLibs.dccLibs import Maya
from liberLibs.utils import save_info
from liberLibs import resource


def open_file(file_name):
    mc.file(file_name, open=1, f=1, loadNoReferences=False, ignoreVersion=1)


def remove_file(path):
    try:
        os.remove(path)
    except:
        logging.error("Can not remove %s." % path)


def convert_maya_files(maya_files):
    if not maya_files:
        return
    for maya_file in maya_files:
        maya_file = maya_file.replace("\\", "/")
        root = os.path.dirname(maya_file)
        root_basename = os.path.basename(root)
        if root_basename in ["ma", "mb"]:
            root = os.path.dirname(root)
            shader_name = os.path.basename(root)
        else:
            shader_name = root_basename
        ext = maya_file.split(".")[-1]
        ext_folder = os.path.join(root, ext).replace("\\", "/")
        if not os.path.isdir(ext_folder):
            os.makedirs(ext_folder)
        new_path = os.path.join(ext_folder, "%s.%s" % (shader_name, ext)).replace("\\", "/")
        if maya_file != new_path:
            shutil.copyfile(maya_file, new_path)
            try:
                remove_file(maya_file)
            except:
                logging.error("[error]: can not remove %s" % maya_file)
        if os.path.isfile(new_path):
            open_file(new_path)
            texture_nodes = Maya.get_all_texture_nodes()
            if texture_nodes:
                texture_dir = os.path.join(root, "texture").replace("\\", "/")
                Maya.export_textures(texture_nodes, texture_dir)
            mc.file(save=1, f=1)


def convert_meta(meta_files):
    if not meta_files:
        return
    for meta_file in meta_files:
        root = os.path.dirname(meta_file)
        try:
            remove_file(meta_file)
        except:
            logging.error("[error]: Can not remove %s" % meta_file)
        json_path = "%s/info.json" % root
        json_path = json_path.replace("\\", "/")
        save_info("", json_path)


def convert_thumbnail(thumbnail_files):
    if not thumbnail_files:
        return
    for thumbnail_file in thumbnail_files:
        root = os.path.dirname(thumbnail_file)
        thumbnail_path = "%s/thumbnail.png" % root
        thumbnail_path = thumbnail_path.replace("\\", "/")
        try:
            os.rename(thumbnail_file, thumbnail_path)
        except:
            logging.error("[error]: can not rename %s" % thumbnail_file)


class SlibToLiber(QDialog):
    def __init__(self, parent=None):
        super(SlibToLiber, self).__init__(parent)
        self.resize(600, 100)
        self.setWindowTitle("Slib2Liber")
        main_layout = QVBoxLayout(self)
        grid_layout = QGridLayout()
        shader_path_label = QLabel("Liber shader path")
        self.shader_le = QLineEdit()
        self.shader_le.setPlaceholderText(u"填入你想转换成Liber能识别的材质球的文件夹路径")
        slib_label = QLabel("SLib env Path")
        self.slib_le = QLineEdit()
        self.slib_le.setReadOnly(True)
        self.slib_le.setPlaceholderText(u"显示SLiBRARY环境变量所指的路径")
        grid_layout.addWidget(shader_path_label, 0, 0, 1, 1)
        grid_layout.addWidget(self.shader_le, 0, 1, 1, 5)
        grid_layout.addWidget(slib_label, 1, 0, 1, 1)
        grid_layout.addWidget(self.slib_le, 1, 1, 1, 5)

        btn_layout = QHBoxLayout()
        self.convert_btn = QPushButton("convert")
        btn_layout.addStretch()
        btn_layout.addWidget(self.convert_btn)
        main_layout.addLayout(grid_layout)
        main_layout.addLayout(btn_layout)

        self.setStyleSheet(resource.style())
        self.convert_btn.clicked.connect(self.convert)
        self.init()

    def init(self):
        env_path = os.getenv("SLiBRARY")
        if env_path:
            self.slib_le.setText(env_path)

    @property
    def shader_dir(self):
        dir_ = self.shader_le.text()
        if dir_:
            dir_ = dir_.replace("\\", "/")
        return dir_

    @property
    def slib_env(self):
        slib = self.slib_le.text()
        if slib:
            slib = slib.replace("\\", "/")
        return slib

    def convert(self):
        if not self.shader_dir or not os.path.isdir(self.shader_dir):
            return
        if not self.slib_env:
            MessageBox.information(self, "Warning",
                                   u"你可能没有安装SLIB,系统无法识别到环境变量SLiBRARY，会导致贴图无法识别。\n\n\n"
                                   u"建议你先启动SLIB或者将SLIB所在的路径添加到系统环境变量中。")
            return
        maya_files = list()
        meta_files = list()
        thumbnail_files = list()
        for root, _dir, files in os.walk(self.shader_dir):
            for f in files:
                path = "%s/%s" % (root, f)
                path = path.replace("\\", "/")
                ext = path.split(".")[-1]
                if ext in ["ma", "mb"]:
                    maya_files.append(path)

                if f.endswith(".meta"):
                    meta_files.append(path)

                if f.endswith(".png") and f != "thumbnail.png" and not os.path.dirname(path).endswith("texture"):
                    thumbnail_files.append(path)

        convert_maya_files(maya_files)
        convert_meta(meta_files)
        convert_thumbnail(thumbnail_files)


if __name__ == "__main__":
    from liberLibs import utils
    with utils.render_ui():
        l = SlibToLiber()
        l.show()
